package com.yong.automoguding.component;

import com.yong.automoguding.adapter.CallToResponseEntityAdapterFactory;
import com.yong.automoguding.annotation.RetrofitApi;
import lombok.extern.java.Log;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.springframework.beans.factory.FactoryBean;
import retrofit2.Retrofit;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Hes
 */
public class RetrofitFactoryBean<T> implements FactoryBean<T> {

    private Class<T> apiInterface;


    private static final OkHttpClient CLIENT;

    static {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .callTimeout(30000, TimeUnit.MILLISECONDS)
                .connectTimeout(30000, TimeUnit.MILLISECONDS)
                .readTimeout(30000, TimeUnit.MILLISECONDS)
                .writeTimeout(30000, TimeUnit.MILLISECONDS);
        CLIENT = builder.build();




    }

    public RetrofitFactoryBean(Class<T> apiInterface) {
        this.apiInterface = apiInterface;
    }


    @Override
    public T getObject() throws Exception {

        RetrofitApi retrofitApi = apiInterface.getAnnotation(RetrofitApi.class);
        String url = retrofitApi.value();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(CLIENT)
                .addConverterFactory(new FastJsonRetrofitConverterFactory())
                .addCallAdapterFactory(new CallToResponseEntityAdapterFactory())
                .build();
        return retrofit.create(apiInterface);
    }

    @Override
    public Class<?> getObjectType() {
        return apiInterface;
    }
}
